package com.github.shiqiyue.xm.filter;

import com.github.shiqiyue.xm.common.Result;
import com.github.shiqiyue.xm.common.ResultMsg;
import com.github.shiqiyue.xm.util.ResponseUtils;
import com.github.shiqiyue.xm.util.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 *
 * @author wenyao.wu
 * @date:2019/8/25
 */
@Slf4j
public class SecurityFilter  extends OncePerRequestFilter {


    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    /***
     * 校验的链接地址
     */
    private List<String> securePathList = new ArrayList<>();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            String servletPath = httpServletRequest.getServletPath();
            boolean isNeedSecurity = false;
            for (String securePath : securePathList) {
                if (antPathMatcher.match(securePath, servletPath)) {
                    isNeedSecurity = true;
                    break;
                }
            }
            if(!isNeedSecurity){
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
            if(!Boolean.TRUE.equals(httpServletRequest.getSession(true).getAttribute("login"))){
                ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.REQUEST_ERROR)), httpServletResponse);
                return;
            }

            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        } catch (Exception e) {
            log.error("timestamp filter 异常", e);
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.REQUEST_ERROR)), httpServletResponse);
            return;
        }
    }

    /***
     * 添加校验的链接地址
     * @param securePath
     * @return
     */
    public SecurityFilter addSecurePath(String securePath) {
        securePathList.add(securePath);
        return this;
    }
}
